import {
    StringUtil
} from "../../../utils/StringUtil";
import {
    Chapter
} from "../model/Chapter";
import {
    Lesson
} from "../model/Lesson";
import {
    Book
} from "../model/Book";
import {
    Publisher
} from "../model/Publisher";
import {
    Downloader
} from "../model/Downloader";
import {
    UserResource
} from "../model/UserResource";
import {
    SqlLibUser
} from "./SqlLibUser";
import {
    UserClassTime
} from "../model/UserClassTime";
import {
    UserClassEvents
} from "../model/UserClassEvents";
const SELF_PPT = "selfPpt";
const SELF_VIDEO = "selfVideo";
const cryUtil = require('../../../utils/CrypUtil')

export class SqlLibBook {

    constructor() { }

    static queryChapterLessonByBookId (sqlLib, bookId) {
        let resultBook = [];
        let chapterSql = StringUtil.format("SELECT * from t_chapter where book_id = '{0}'", bookId);
        let chapters = sqlLib.runSql(chapterSql);
        if (sqlLib.checkSqlError(chapters)) {
            if (chapters[0]) {
                chapters.forEach(chapter => {
                    let tempC = new Chapter();
                    tempC = tempC.mappingModel(chapter);
                    let lessonSql = StringUtil.format("select * from t_lesson where chapter_id = '{0}'", chapter.id);
                    let lessons = sqlLib.runSql(lessonSql);
                    if (sqlLib.checkSqlError(lessons)) {
                        if (lessons[0]) {
                            tempC.lessonVO = [];
                            lessons.forEach(lesson => {
                                let tempL = new Lesson();
                                tempL = tempL.mappingModel(lesson);
                                tempC.lessonVO.push(tempL);
                            });
                            resultBook.push(tempC);
                        }
                    }
                });
                return resultBook;
            } else {
                return null;
            }
        } else {
            return chapters;
        }
    }

    static queryChaAndBookNameByLessonId (sqlLib, lessonId) {
        let result = {
            chapterName: "",
            bookName: "",
            publisherName: "",
            lessonName: ""
        }
        if (!lessonId) {
            return result;
        }
        let lesson = new Lesson();
        lesson.id = lessonId;
        lesson = sqlLib.selectObjectById(lesson);
        result.lessonName = lesson.name;

        let chapterId = lesson.chapterId;
        if (chapterId) {
            let chapter = new Chapter();
            chapter.id = chapterId;
            chapter = sqlLib.selectObjectById(chapter);
            result.chapterName = chapter.name;
            if (lesson.reverse3 == 'userDiy') {
                result.bookName = '我的课程';
                result.publisherName = 'Diy课程';
            }else{
                if (chapter.bookId) {
                    let book = new Book();
                    console.log('book.name',book.name);
                    book.id = chapter.bookId;
                    book = sqlLib.selectObjectById(book);
                    result.bookName = book.name;
                    if (book.name == '我的课程') {
                        result.publisherName = 'Diy课程';
                    }else{
                        if (book.publisherId) {
                            let publisher = new Publisher();
                            publisher.id = book.publisherId;
                            publisher = sqlLib.selectObjectById(publisher);
                            result.publisherName = publisher.name;
                        }
                    }
                }
            }
        }
        return result;
    }

    static queryBookAndCharpterByLessonId (sqlLib, lessonId) {
        let result = {
            lessonId: lessonId,
            chapterId: "",
            bookId: ""
        }
        if (!lessonId) {
            return result;
        }
        let lesson = new Lesson();
        lesson.id = lessonId;
        lesson = sqlLib.selectObjectById(lesson);

        let chapterId = lesson.chapterId;
        if (chapterId) {
            let chapter = new Chapter();
            chapter.id = chapterId;
            chapter = sqlLib.selectObjectById(chapter);
            result.chapterId = chapterId;
            result.bookId = chapter.bookId;
        }
        return result;
    }

    static updateOrInsertOneResource (sqlLib, obj) {
        
        if (!obj.symbolName || !obj.tableName || !obj.lessonId || !obj.userId || !obj.resourceId) {
            return "param error"
        } else {
            let selectSql = StringUtil.format("select * from t_user_resource where user_id = '{0}' and lesson_id = '{1}' and resource_id = '{2}'", obj.userId, obj.lessonId, obj.resourceId);
            let userResource = sqlLib.runSql(selectSql);
            if (!userResource) {
                return sqlLib.insertObject(obj);
            }
            if (sqlLib.checkSqlError(userResource)) {
                //表示可以从库里查到
                if (userResource[0]) {
                    obj.id = userResource[0].id
                    return sqlLib.updateObjectById(obj);
                } else {
                    return sqlLib.insertObject(obj);
                }
            } else {
                return userResource;
            }
        }
    }

    static queryUnDownloadLesson (sqlLib) {
        let sql = StringUtil.format("select * from t_downloader where downloader_status = '0' order by fill_time")
        let result = sqlLib.runSql(sql);
        let objResult = [];
        let downloader = new Downloader();
        result.forEach(temp => {
            objResult.push(downloader.mappingModel(temp));
        });
        return objResult;
    }

    static queryOneResource (sqlLib, userId, lessonId, resourceId) {
        let selectSql = StringUtil.format("select * from t_user_resource where user_id = '{0}' and lesson_id = '{1}' and resource_id = '{2}' ", userId, lessonId, resourceId);
        let userResource = sqlLib.runSql(selectSql);
        if (sqlLib.checkSqlError(userResource)) {
            if (userResource[0]) {
                return (new UserResource()).mappingModel(userResource[0]);
            } else {
                return null;
            }
        } else {
            return userResource;
        }
    }
    static queryOneResourceByName (sqlLib, userId, lessonId,displayName) {
        let selectSql = StringUtil.format("select * from t_user_resource where user_id = '{0}' and lesson_id = '{1}' and resource_name = '{2}'", userId, lessonId,displayName);
        let userResource = sqlLib.runSql(selectSql);
        if (sqlLib.checkSqlError(userResource)) {
            if (userResource[0]) {
                return (new UserResource()).mappingModel(userResource[0]);
            } else {
                return null;
            }
        } else {
            return userResource;
        }
    }
    static queryAllLessonInfoByBookId (sqlLib,bookId) {
        let result = [];
        if (bookId) {
            let book = new Book();
            book.id = bookId;
            book = sqlLib.selectObjectById(book);

            let publisher = new Publisher();
            if (book.publisherId) {
                publisher.id = book.publisherId;
                publisher = sqlLib.selectObjectById(publisher);
            }
            let lessonSql = StringUtil.format("SELECT id, name FROM t_lesson WHERE chapter_id IN ( SELECT id FROM t_chapter WHERE book_id = '{0}' )", bookId);
            let lessonResult = sqlLib.runSql(lessonSql);
            if (sqlLib.checkSqlError(lessonResult)) {
                lessonResult.forEach(lesson => {
                    result.push({
                        SetDownloadId: lesson.id,
                        DownloaderInfo: {
                            lessonName: lesson.name,
                            bookName: book.name,
                            publisherName: publisher.name
                        },
                        ActionStatus: "0" //动作的状态：0 - 下载；1 - 更新；2 - 同步
                    })
                });
                return result;
            } else {
                return lessonResult;
            }
        }
    }
    static deleteAllLessonInfoByBookId (sqlLib,params){
        if (!params.lessonId ) {
            return "param error";
        }
        let user = SqlLibUser.queryCurrentUser(sqlLib);
        params.userId = user.id;
        let sql = StringUtil.format("delete from t_user_resource where user_id = '{0}' and lesson_id = '{1}'", params.userId, params.lessonId,);
        console.log(sql);
        return sqlLib.runSql(sql);
    }
    /**
     * 更新或者插入其他的资源（自己导入的ppt、视频、云资源等）
     * @param sqlLib
     * @param userRes  不需要传sortIndex，由系统自动排序
     * @return {string}
     */
    static updateOrInsertExtraResource (sqlLib, userRes) {
        if (userRes.symbolName !== 'UserResource' || userRes.tableName !== 't_user_resource' || userRes.sortIndex !== -1 ||
            !userRes.userId || !userRes.lessonId || !userRes.resourceId || !userRes.resourceClassify || userRes.resourceClassify === '2') {
            return "param error";
        }
        let selectSql = StringUtil.format("select * from t_user_resource where user_id = '{0}' and lesson_id = '{1}' and resource_id = '{2}'",
            userRes.userId, userRes.lessonId, userRes.resourceId);
        let userResource = sqlLib.runSql(selectSql);
        // console.log('userResource',userResource);
        if (sqlLib.checkSqlError(userResource)) {
            if (userResource[0]) { //如果有这个资源，就更新
                sqlLib.updateObjectById(userRes);
            } else { //如果是插入的话，需要更新其他索引
                if (userRes.resourceClassify === "0") { //自己导入的资源，排在前面
                    if (userRes.resourceType === SELF_PPT) {
                        let courwseSql = StringUtil.format("select * from t_user_resource where user_id = '{0}' and lesson_id = '{1}' and " +
                            "(resource_type = 'selfPpt') order by sort_index desc limit 1",
                            userRes.userId, userRes.lessonId);
                        let lastPpt = sqlLib.runSql(courwseSql);
                        let lastPptIndex = 0;
                        if (sqlLib.checkSqlError(lastPpt)) {
                            if (lastPpt[0]) {
                                lastPptIndex = lastPpt[0].sort_index;
                            }
                            //1.先更新其他资源索引
                            let indexSql = StringUtil.format("update t_user_resource set sort_index = sort_index + 1 where user_id = '{0}' and lesson_id = '{1}' and sort_index > {2}",
                                userRes.userId, userRes.lessonId, lastPptIndex);
                            sqlLib.runSql(indexSql);
                            userRes.sortIndex = lastPptIndex + 1;
                            return sqlLib.insertObject(userRes);
                        } else {
                            return lastPpt;
                        }
                    }else if (
                    userRes.resourceType == 'selfPdf' ||
                    userRes.resourceType == 'selfWord' ||
                    userRes.resourceType == 'selfImg' ||
                    userRes.resourceType == 'selfVideo' ||
                    userRes.resourceType == 'selfAudio' ) {
                        let quizSql = StringUtil.format("select * from t_user_resource where user_id = '{0}' and lesson_id = '{1}' and " +
                        "resource_type != 'Quiz' order by sort_index desc limit 1",
                        userRes.userId, userRes.lessonId);
                        let lastQuiz = sqlLib.runSql(quizSql);
                        let lastQuizIndex = 0;
                        if (sqlLib.checkSqlError(lastQuiz)) {
                            if (lastQuiz[0]) {
                                lastQuizIndex = lastQuiz[0].sort_index;
                            }
                            //1.先更新其他Quiz资源索引
                            let indexSql = StringUtil.format("update t_user_resource set sort_index = sort_index + 1 where user_id = '{0}' and lesson_id = '{1}' and sort_index > {2}",
                                userRes.userId, userRes.lessonId, lastQuizIndex);
                            sqlLib.runSql(indexSql);
                            userRes.sortIndex = lastQuizIndex + 1;
                            return sqlLib.insertObject(userRes);
                        }else {
                            return null;
                        }
                    }
                } else if (userRes.resourceClassify === "1") { //云资源库的资源，排在Quiz前面
                    let quizSql = StringUtil.format("select * from t_user_resource where user_id = '{0}' and lesson_id = '{1}' and " +
                        "resource_type != 'Quiz' order by sort_index desc limit 1",
                        userRes.userId, userRes.lessonId);
                    let lastQuiz = sqlLib.runSql(quizSql);
                    let lastQuizIndex = 0;
                    if (sqlLib.checkSqlError(lastQuiz)) {
                        if (lastQuiz[0]) {
                            lastQuizIndex = lastQuiz[0].sort_index;
                        }
                        //1.先更新其他Quiz资源索引
                        let indexSql = StringUtil.format("update t_user_resource set sort_index = sort_index + 1 where user_id = '{0}' and lesson_id = '{1}' and sort_index > {2}",
                            userRes.userId, userRes.lessonId, lastQuizIndex);
                        sqlLib.runSql(indexSql);
                        userRes.sortIndex = lastQuizIndex + 1;
                        return sqlLib.insertObject(userRes);
                    }
                } else {
                    return null;
                }
            }
        } else {
            return userResource;
        }
    }

    /**
     * 查询已经下载过的云资源+
     * @param sqlLib
     * @param userRes
     */
    static selectDownloadedCloudRes (sqlLib, userRes) {
        if (userRes.symbolName !== 'UserResource' || userRes.tableName !== 't_user_resource' ||
            !userRes.userId || !userRes.lessonId || userRes.resourceClassify !== '1') {
            return "param error";
        }
        let resSql = StringUtil.format("select resource_id from t_user_resource where resource_classify = '1' and lesson_id = '{0}' and user_id = '{1}'", userRes.lessonId, userRes.userId);
        let resourceSqlIds = sqlLib.runSql(resSql);
        let resourceIds = [];
        resourceSqlIds.forEach(id => {
            resourceIds.push(id.resource_id);
        });
        return resourceIds;
    }

    /**
     * 设置默认ppt
     * @param sqlLib
     * @param params {lessonId: "", userId: "", resourceId: ""}
     */
    static setDefaultPpt (sqlLib, params) {
        if (!params.lessonId || !params.resourceId) {
            return "param error";
        }
        let user = SqlLibUser.queryCurrentUser(sqlLib);
        params.userId = user.id;
        let sql = StringUtil.format("update t_user_resource set is_default = '0' where is_default = '1' and user_id = '{0}' and lesson_id = '{1}'", params.userId, params.lessonId);
        console.log(sql);
        sqlLib.runSql(sql);

        let updateSql = StringUtil.format("update t_user_resource set is_default = '1' where  user_id = '{0}' and lesson_id = '{1}' and resource_id = '{2}'",
            params.userId, params.lessonId, params.resourceId);
        console.log(updateSql);
        return sqlLib.runSql(updateSql);
    }
    // 重置默认PPT
    static resetDefaultPpt (sqlLib, lessonId) {
        if (!lessonId) {
            return "param error";
        }
        let sql = StringUtil.format("update t_user_resource set is_default = '0' where  lesson_id = '{0}' and is_default = '1'", lessonId);
        sqlLib.runSql(sql);
    }
    /**
     * 删除课程关联的资源
     * @param sqlLib
     * @param params
     * @return {*}
     */
    static deleteLessonResource (sqlLib, params) {
        if (!params.lessonId || !params.resourceId) {
            return "param error";
        }
        let user = SqlLibUser.queryCurrentUser(sqlLib);
        params.userId = user.id;
        let sql = StringUtil.format("delete from t_user_resource where user_id = '{0}' and lesson_id = '{1}' and resource_id = '{2}'", params.userId, params.lessonId, params.resourceId);
        console.log(sqlLib.runSql(sql));
        return sqlLib.runSql(sql);
    }

    //删除用户所有已下载的课程
    static deleteAllDownloadedLessonByUserId (sqlLib,userId) {
        const sql = StringUtil.format("delete from t_download_complete where user_id = '{0}'", userId);
        console.log(sqlLib.runSql(sql));
        return sqlLib.runSql(sql);
    }

    static queryPublisher (sqlLib, eduLevelId) {
        if (!sqlLib) {
            return 'error'
        }
        let sql = StringUtil.format('select * from t_publisher where edu_level_id = {0} order by id', eduLevelId)
        let res = sqlLib.runSql(sql)
        // console.log('queryPublisher====>'+JSON.stringify(res))
        if (sqlLib.checkSqlError(res)) {
            if (res[0]) {
                let temp = new Publisher()
                let resArr = []
                res.forEach(v => {
                    resArr.push(temp.mappingModel(v))
                })
                return resArr
            } else {
                return null
            }
        } else {
            res
        }

    }
    static queryPublisherIdBybookId (sqlLib, bookId) {
        if (!sqlLib) {
            return 'error'
        }
        let sql = StringUtil.format('select publisher_id from t_book where id = {0}', bookId)
        let res = sqlLib.runSql(sql)
        // console.log('queryPublisher====>'+JSON.stringify(res))
        if (sqlLib.checkSqlError(res)) {
            if (res[0]) {
                return res[0].publisher_id
            } else {
                return null
            }
        } else {
            res
        }

    }
    static queryPublisherTypeBybookId (sqlLib, PublisherId) {
        if (!sqlLib) {
            return 'error'
        }
        let sql = StringUtil.format('select * from t_publisher where id = {0}', PublisherId)
        let res = sqlLib.runSql(sql)
        // console.log('res-------------',res);
        if (sqlLib.checkSqlError(res)) {
            if (res[0]) {
                let temp = new Book()
                let resArr = []
                res.forEach(v => {
                    resArr.push(temp.mappingModel(v))
                })
                return resArr
            } else {
                return null
            }
        } else {
            res
        }
    }
    static queryBookByEitionId (sqlLib, editionId) {
        if (!sqlLib) {
            return 'error'
        }
        let sql = StringUtil.format("select * from t_book where publisher_id = '{0}' order by sort_index ", editionId)
        let res = sqlLib.runSql(sql)
        if (sqlLib.checkSqlError(res)) {
            if (res[0]) {
                let temp = new Book()
                let resArr = []
                res.forEach(v => {
                    resArr.push(temp.mappingModel(v))
                })
                return resArr
            } else {
                return null
            }
        } else {
            res
        }

    }

    static queryAllBooks (sqlLib) {
        if (!sqlLib) {
            return 'error'
        }
        let sql = StringUtil.format("select * from t_book order by sort_index")
        let res = sqlLib.runSql(sql)
        if (sqlLib.checkSqlError(res)) {
            if (res[0]) {
                let temp = new Book()
                let resArr = []
                res.forEach(v => {
                    resArr.push(temp.mappingModel(v))
                })
                return resArr
            } else {
                return null
            }
        } else {
            res
        }

    }
    static updateBookAuthorization (sqlLib, bookId) {
        if (!sqlLib) {
            return 'error'
        }
        let result = "";
        if (bookId) {
            let authMsg = cryUtil.aesEncrypt('已授权', bookId + "", true);
            let sql = StringUtil.format("update t_book set is_authorize = '{0}' where id = '{1}'", authMsg, bookId);
            result = sqlLib.runSql(sql);
        } else {
            let tempBook = new Book();
            let allBooks = sqlLib.selectAllObject(tempBook);
            allBooks.forEach(book => {
                let authMsg = cryUtil.aesEncrypt('已授权', book.id + "", true);
                let sql = StringUtil.format("update t_book set is_authorize = '{0}' where id = '{1}'", authMsg, book.id);
                result = sqlLib.runSql(sql);
            })
            if (sqlLib.checkSqlError(result)) {
                return result
            } else {
                return result
            }
        }
    }

    static queryDefaultPpt (sqlLib, lessonId) {
        if (!sqlLib) {
            return 'error'
        }
        let user = SqlLibUser.queryCurrentUser(sqlLib);
        let querySql = StringUtil.format("select * from t_user_resource where is_default = '1' and (resource_type = 'courseware' or resource_type = 'selfPpt') and lesson_id = '{0}' and user_id = '{1}'", lessonId, user.id);
        let res = sqlLib.runSql(querySql);
        if (sqlLib.checkSqlError(res)) {
            if (res[0]) {
                let userResource = new UserResource();
                userResource = userResource.mappingModel(res[0]);
                return userResource
            } else {
                return null
            }
        } else {
            return res;
        }
    }

    static querAllClassTime (sqlLib) {
        if (!sqlLib) return 'error'
        let sql = 'select * from t_rec_user_class_time'
        let res = sqlLib.runSql(sql)
        if (sqlLib.checkSqlError(res)) {
            if (res[0]) {
                let temp = new UserClassTime()
                let tempArr = []
                res.forEach(v => {
                    tempArr.push(temp.mappingModel(v))
                })
                return tempArr
            } else {
                return null
            }
        } else {
            return res
        }
    }
    static querLastClassEvents (sqlLib) {
        if (!sqlLib) return 'error'
        let user = SqlLibUser.queryCurrentUser(sqlLib)
        let sql = StringUtil.format("select * from t_rec_user_class_events where user_id = '{0}' order by rowid desc limit 1", user.id)
        let res = sqlLib.runSql(sql)
        if (sqlLib.checkSqlError(res)) {
            if (res[0]) {
                let temp = new UserClassEvents()
                return temp.mappingModel(res[0])
            } else {
                return null
            }
        } else {
            return res
        }
    }
    static insertEndClassTime (sqlLib, params) {
        if (!sqlLib) return 'params error'
        let lastClassEvent = this.querLastClassEvents(sqlLib)
        if (lastClassEvent) {
            let event = lastClassEvent
            if (event.type === '0') {
                if ((new Date(params.createTime) - new Date(event.createTime)) < 2 * 60 * 1000) {
                    sqlLib.deleteObjectById(event)
                    return
                } else {
                    params.relateStartId = event.id
                    sqlLib.insertObject(params)
                    let classTime = new UserClassTime()
                    classTime.id = event.id
                    classTime.userId = event.userId
                    classTime.reverse1 = event.createTime
                    let time = new Date(params.createTime) - new Date(event.createTime)
                    classTime.btwTime = time > 45 * 60 * 1000 ? 45 : parseInt(time / 1000 / 60)
                    sqlLib.insertObject(classTime)
                }
            }
        }
    }
    static clearEventsTable (sqlLib) {
        if (!sqlLib) return 'error'
        let sql = 'DELETE FROM t_rec_user_class_events'
        return sqlLib.runSql(sql)
    }
    static clearClassTimeTable (sqlLib) {
        if (!sqlLib) return 'error'
        let sql = 'DELETE FROM t_rec_user_class_time'
        return sqlLib.runSql(sql)
    }
}
